package com.hq.fxh.No1_Infromation.Video.Activity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.MediaMetadataRetriever;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hq.fxh.R;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.ThreadPoolUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by 薛文豪 视频录制
 */
public class VideoAddActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback {
    //+ File.separator + "egoo"
    public static final String RECORD_VIDEO_PATH = Environment.getExternalStorageDirectory() + "/DCIM/movie/";
    protected SurfaceView mSurfaceView;
    protected LinearLayout videoStart;
    protected ImageView videoYes;
    protected ImageView videoNo;
    protected RelativeLayout mainPressControl;
    protected RelativeLayout activityMain3;
    protected Chronometer timer;
    protected LinearLayout baseBack;
    protected TextView baseTitle;
    protected RelativeLayout baseSent;
    protected LinearLayout baseLayout;
    protected ImageView videoChange;
    protected ProgressBar videoAddProgress;
    protected LinearLayout layoutStop;
    private Camera mCamera;
    private View mStartButton;    //底部"按住拍"按钮
    private Thread mProgressThread;  //进度条线程
    private MediaRecorder mMediaRecorder;  //录制视频
    private SurfaceHolder mSurfaceHolder;
    private int videoWidth, videoHeight;  //屏幕分辨率
    private boolean isRecording; //判断是否正在录制
    private File mTargetFile; //段视频保存的目录
    private GestureDetector mDetector;//手势处理, 主要用于变焦 (双击放大缩小)
    private boolean isZoomIn = false;  //是否放大
    private boolean isRunning;
    private static long downSec;
    private static Boolean isRec;
    private Handler mHandler1;
    private Boolean notNull;
    private boolean isCameraBack;
    private int cameraPosition = 1;
    private int maxTime = 30;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String s = timer.getText().toString();

            String[] split = s.split(":");
            if (split != null && split.length == 2) {
                try {
                    Integer decode = Integer.parseInt(split[0]);
                    Integer decode2 = Integer.parseInt(split[1]);
                    int progress = decode * 60 + decode2;
                    if (progress < maxTime) {
                        videoAddProgress.setProgress(progress);
                        if (progress % 3 == 0) {
                            autoFocus();
                        }
                    } else {
                        videofinish();
                    }
                } catch (Exception e) {

                }

            } else {
            }

        }
    };

    private Timer mTimer;

    private void setTimerTask() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {

                handler.sendEmptyMessage(1);

            }
        }, 1000, 1000/* 表示1000毫秒之後，每隔1000毫秒執行一次 */);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mTimer.cancel();
        timer.stop();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_addvideo);
        mTimer = new Timer();
        // start timer task

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.black));
        }

        isRec = false;
        notNull = false;
        mHandler1 = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 1001) {
                    notNull = true;
                } else if (msg.what == 1002) {
                    notNull = false;
                }
                return false;
            }
        });
        initView();
        initData();
        initZoom();

    }

    private void initZoom() {
        mDetector = new GestureDetector(this, new ZoomGestureListener());
        /**
         * 单独处理mSurfaceView的双击事件
         */
        mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mDetector.onTouchEvent(event);
                return true;
            }
        });

    }

    private void initData() {
        videoWidth = 640;
        videoHeight = 480;
        mDetector = new GestureDetector(this, new ZoomGestureListener());
        mMediaRecorder = new MediaRecorder();
        mSurfaceHolder = mSurfaceView.getHolder();
        //设置屏幕分辨率
        mSurfaceHolder.setFixedSize(videoWidth, videoHeight);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.addCallback(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.layout_start) {
            videoStart.setVisibility(View.GONE);
            layoutStop.setVisibility(View.VISIBLE);
            if (!isRec && notNull == false) {
                Message message = Message.obtain();
                message.what = 1001;
                timer.setBase(SystemClock.elapsedRealtime());//计时器清零
                timer.start();
                setTimerTask();
                tvReset();
                tvStart();
                mHandler1.sendMessageDelayed(message, 1500);
                startRecord();
                baseSent.setVisibility(View.GONE);
            }


        } else if (view.getId() == R.id.video_no) {
            //   videofinish();
            stopRecordUnSave();
            finish();

        } else if (view.getId() == R.id.video_yes) {

            if (isRec) {
                Message message = Message.obtain();
                message.what = 1002;
                mHandler1.sendMessage(message);
                videofinish();
                timer.setBase(SystemClock.elapsedRealtime());
                timer.stop();
                mTimer.cancel();

                long length = mTargetFile.length();
                //    Intent intent = new Intent(this, VideoPlayActivity.class);
                Intent intent = new Intent(this, VideoUpdateActivity.class);
                intent.putExtra("path", mTargetFile.getAbsolutePath());
                startActivity(intent);
                LogUtils.e(" tiao zhuan bofang" + mTargetFile.getAbsolutePath());
                this.finish();
            } else {
                timer.stop();
                mTimer.cancel();
                tvPause();

                try {
                    mMediaRecorder.stop();
                } catch (RuntimeException e) {
                    Log.e("视频录制停止", ""); //you must delete the outputfile when the recorder stop failed.
                } finally {

                }
                Toast.makeText(this, "视频尚未录制，请点击录制按钮！", Toast.LENGTH_LONG);

            }
        } else if (view.getId() == R.id.video_back) {
            if (isRecording) {
                stopRecordUnSave();
                finish();
            } else {
                finish();
            }

        } else if (view.getId() == R.id.video_sent) {
            if (!isRec && notNull == false) {
                change(view);
            } else {
                LogUtils.startToash(this, "摄像头转换失败");
            }

            //   toast("暂未开放该功能");
        }
    }

    private void videofinish() {
         if (notNull == true) {
            timer.stop();
            mTimer.cancel();
            tvReset();
            stopRecordSave();

        } else {
            LogUtils.e("videoAdd___notNull为空");
        }
    }


    private void initView() {
        mSurfaceView = (SurfaceView) findViewById(R.id.myVideo_surface);
        videoStart = (LinearLayout) findViewById(R.id.layout_start);
        videoStart.setOnClickListener(VideoAddActivity.this);
        videoYes = (ImageView) findViewById(R.id.video_yes);
        videoYes.setOnClickListener(VideoAddActivity.this);
        videoNo = (ImageView) findViewById(R.id.video_no);
        videoNo.setOnClickListener(VideoAddActivity.this);
        mainPressControl = (RelativeLayout) findViewById(R.id.main_press_control);
        activityMain3 = (RelativeLayout) findViewById(R.id.activity_main3);
        timer = (Chronometer) findViewById(R.id.timer);
        baseBack = (LinearLayout) findViewById(R.id.video_back);
        baseBack.setOnClickListener(VideoAddActivity.this);
        baseTitle = (TextView) findViewById(R.id.video_title);
        baseTitle.setOnClickListener(VideoAddActivity.this);
        baseSent = (RelativeLayout) findViewById(R.id.video_sent);
        baseSent.setOnClickListener(VideoAddActivity.this);
        baseLayout = (LinearLayout) findViewById(R.id.video_layout);
        baseTitle.getPaint().setFakeBoldText(true);
        videoChange = (ImageView) findViewById(R.id.video_change);
        videoAddProgress = (ProgressBar) findViewById(R.id.videoAdd_progress);
        videoAddProgress.setMax(maxTime);
        layoutStop = (LinearLayout) findViewById(R.id.layout_stop);
        layoutStop.setOnClickListener(VideoAddActivity.this);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mSurfaceHolder = holder;
        startPreView(holder);
    }

    private Camera.AutoFocusCallback mAutoFocusCallback;

    /**
     * 开启预览
     *
     * @param holder
     */
    private void startPreView(SurfaceHolder holder) {
        if (mCamera == null) {
            try {
                mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                mCamera.setDisplayOrientation(90);
            } catch (Exception e) {
                finish();
            }
        }

        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
        }
        if (mCamera != null) {
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (mCamera == null) {
            Toast.makeText(this, "摄像头调用失败", Toast.LENGTH_SHORT).show();
            return;
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format,
                               int width, int height) {
        autoFocus();
    }

    public void autoFocus() {
        //实现自动对焦
        mCamera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
                }
            }

        });
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            //停止预览并释放摄像头资源
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        if (mMediaRecorder != null) {
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }


    // 进度条结束后的回调方法
/*    @Override
    public void onProgressEndListener() {
        //视频停止录制
        stopRecordSave();
    }*/

    /**
     * 开始录制
     */

    private void startRecord() {
        isRec = true;
        downSec = System.currentTimeMillis();
        if (mMediaRecorder != null) {
            //没有外置存储, 直接停止录制
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return;
            }
            if (cameraPosition == 1) {
                //     mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);//打开摄像头
//				 camera = Camera.open(cameraPosition);//打开摄像头
//		         Camera.Parameters parameters = camera.getParameters();
                mCamera.setDisplayOrientation(90);
//		         camera.setParameters(parameters);
                mMediaRecorder.setOrientationHint(90);//视频旋转90度
            } else {
//            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);//打开摄像头
                Camera.Parameters parameters = mCamera.getParameters();
                mCamera.setDisplayOrientation(90);
                mCamera.setParameters(parameters);
                mMediaRecorder.setOrientationHint(270);//视频旋转90度
            }
            mCamera.unlock();
            mMediaRecorder.setCamera(mCamera);
            //从相机采集视频
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            // 从麦克采集音频信息
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            //  设置视频格式
            //                mMediaRecorder.setProfile(CamcorderProfile
            //                        .get(CamcorderProfile.QUALITY_HIGH));
            mMediaRecorder.setVideoSize(videoWidth, videoHeight);
            //每秒的帧数 有的手机不支持
            try {
                mMediaRecorder.setVideoFrameRate(20);

            } catch (Exception e) {
            }
            //编码格式
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

            // 设置帧频率，然后就清晰了 有的手机不支持
            try {
                mMediaRecorder.setVideoEncodingBitRate(2 * 1024 * 1024);

            } catch (Exception e) {
            }

            //  临时写个文件地址, 稍候改!!!
            File dir = new File(RECORD_VIDEO_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            mTargetFile = new File(dir,
                    "RIDEO_haiqu" + SystemClock.currentThreadTimeMillis() + ".mp4");
            mMediaRecorder.setOutputFile(mTargetFile.getAbsolutePath());
            mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            //解决录制视频, 播放器横向问题
            try {
                mMediaRecorder.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //正式录制
            mMediaRecorder.start();
            isRecording = true;

        }
    }

    /**
     * 停止录制 并且保存
     */
    private void stopRecordSave() {
        tvReset();
        if (isRecording) {
            isRunning = false;
            try {
                mMediaRecorder.stop();
                isRecording = false;
                //        getIconFile(mTargetFile.getAbsolutePath());
            } catch (Exception e) {
            }
        }
        setfile(mTargetFile.getAbsolutePath(),mTargetFile.getName(),mTargetFile.length());
    }

    /**
     * 停止录制, 不保存
     */
    private void stopRecordUnSave() {

        tvReset();
        isRec = false;

        if (mTargetFile.exists()) {
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {

                    try {
                        mTargetFile.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
     /*   final File pictureFile = new File(mTargetFile.getAbsolutePath().replaceAll(".mp4", ".jpg"));
        if (pictureFile.exists()) {
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    pictureFile.delete();
                }
            });
        }*/
        //   finish();
    }


    /**
     * 相机变焦
     *
     * @param zoomValue
     */
    public void setZoom(int zoomValue) {
        if (mCamera != null) {
            mCamera.setDisplayOrientation(90);
            Camera.Parameters parameters = mCamera.getParameters();
            if (parameters.isZoomSupported()) {//判断是否支持
                int maxZoom = parameters.getMaxZoom();
                if (maxZoom == 0) {
                    return;
                }
                if (zoomValue > maxZoom) {
                    zoomValue = maxZoom;
                }
                parameters.setZoom(zoomValue);
                mCamera.setParameters(parameters);

            }
        }

    }

    // 变焦手势处理类
    class ZoomGestureListener extends GestureDetector.SimpleOnGestureListener {
        //双击手势事件
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            super.onDoubleTap(e);
            if (mMediaRecorder != null) {
                if (!isZoomIn) {
                    setZoom(10);
                    isZoomIn = true;
                } else {
                    setZoom(0);
                    isZoomIn = false;
                }
            }
            autoFocus();
            return true;
        }
    }

    protected void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否保存视频文件？");

        builder.setTitle("提示");

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();

            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                stopRecordUnSave();
                dialog.dismiss();
                finish();
            }
        });

        builder.create().show();
    }

    @NonNull
    public void getIconFile(String videoPath) {
        Log.e("保存视频地址", videoPath);
        String iconPath = videoPath.replaceAll(".mp4", ".jpg");
        Log.e("保存图片地址", iconPath);
        File icon = new File(iconPath);

        String state = Environment.getExternalStorageState();
//如果状态不是mounted，无法读写
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            return;
        }

        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(videoPath);
        Bitmap bitmap = mmr.getFrameAtTime();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(icon));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void tvStart() {
        // videoYes.setTextColor(getResources().getColor(R.color.black));
        // videoNo.setTextColor(getResources().getColor(R.color.black));

    }

    private void tvPause() {
        //  videoYes.setTextColor(getResources().getColor(R.color.grey));
        //  videoNo.setTextColor(getResources().getColor(R.color.grey));
    }

    private void tvReset() {

        //   videoYes.setTextColor(getResources().getColor(R.color.grey));
        // videoNo.setTextColor(getResources().getColor(R.color.grey));
    }


    public void change(View v) {
        //切换前后摄像头
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
            if (cameraPosition == 1) {
                //现在是后置，变更为前置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                    mCamera.stopPreview();//停掉原来摄像头的预览
                    mCamera.release();//释放资源
                    mCamera = null;//取消原来摄像头
                    mCamera = Camera.open(i);//打开当前选中的摄像头
                    try {
                        mCamera.setPreviewDisplay(mSurfaceHolder);//通过surfaceview显示取景画面
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mCamera.startPreview();//开始预览
                    mCamera.setDisplayOrientation(90);

                    cameraPosition = 0;
                    break;
                }
            } else {
                //现在是前置， 变更为后置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                    mCamera.stopPreview();//停掉原来摄像头的预览
                    mCamera.release();//释放资源
                    mCamera = null;//取消原来摄像头
                    mCamera = Camera.open(i);//打开当前选中的摄像头
                    try {
                        mCamera.setPreviewDisplay(mSurfaceHolder);//通过surfaceview显示取景画面
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    mCamera.startPreview();//开始预览
                    mCamera.setDisplayOrientation(90);
                    cameraPosition = 1;
                    break;
                }
            }

        }
    }

    public void setfile(String fileName,String name, long size){
        ContentValues localContentValues = new ContentValues();
        localContentValues.put(MediaStore.Video.Media.DATA, fileName);
        localContentValues.put(MediaStore.Video.Media.TITLE, name);
        localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        localContentValues.put(MediaStore.Video.Media.SIZE, size);
        localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, name);
        ContentResolver localContentResolver = getContentResolver();
        Uri localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        localContentResolver.insert(localUri, localContentValues);
    }
}
